/**
 * 
 */
package jfengao.oauth.client;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import jfengao.oauth.client.common.IO;
import jfengao.oauth.client.common.OauthString;

/**
 * 
 * @author gaofeng
 * @date 2018年9月17日
 */
public class SimpleNetworkExecutor implements HttpExecutor {
	
	Map<String,String> heads = new HashMap<String,String>();
	Map<String,String> params = new HashMap<String,String>();

	public SimpleNetworkExecutor() {
	}

	public String execute(OauthClient oauthClient) {
		OauthInfo oauthinfo  = oauthClient.getOauthinfo();
		String wwwBasic      = OauthString.wwwBasicAuth(oauthinfo.getClientId(), oauthinfo.getClientSecret());
		String requestTarget = OauthString.builderURI(oauthinfo);
		System.err.println(wwwBasic);
		System.err.println(requestTarget); 
		HttpURLConnection connection = null;
		InputStream ins = null;
		try {
			String getMoreParas = additionalParams();
			connection = newHttpURLConnection(requestTarget + getMoreParas);
			connection.setRequestProperty("Authorization", wwwBasic);
			connection.setRequestProperty("Content-Type", HttpHeader.ContentType);
			connection.setRequestProperty("Accept", HttpHeader.Accept);
			additional(connection);
			ins = connection.getInputStream();
			byte[] data = IO.readFromInputStream(ins);
			return new String(data);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) 
				connection.disconnect();
			if (ins != null)
				try {
					ins.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return null;
	}

	private String additionalParams() {
		Set<Entry<String,String>> sets = params.entrySet();
		StringBuilder sb = new StringBuilder();
		for (Entry<String,String> e : sets) {
			sb.append("&").append(e.getKey()).append("=").append(e.getValue());
		}
		return sb.toString();
	}

	private void additional(HttpURLConnection connection) {
		Set<Entry<String,String>> sets = heads.entrySet();
		for (Entry<String,String> e : sets) {
			connection.setRequestProperty(e.getKey(), e.getValue()); 
		}
	}

	HttpURLConnection newHttpURLConnection(String target) throws IOException {
		URL url = new URL(target);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setConnectTimeout(3000);
		connection.setReadTimeout(3000);
		connection.setRequestMethod("POST");
		return connection;
	}

	@Override
	public void addHeader(String key, String val) {
		heads.put(key, val);
	}

	@Override
	public void addParam(String key, String val) {
		params.put(key, val);
	}
	
}
